package com.ccteam.admin.view.fragments.artist

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.bumptech.glide.Glide
import com.ccteam.admin.R
import com.ccteam.admin.REFRESH_REQUEST_KEY
import com.ccteam.admin.core.ADD_TYPE
import com.ccteam.admin.core.EDIT_TYPE
import com.ccteam.admin.databinding.FragmentArtistEditBinding
import com.ccteam.admin.utils.EventObserver
import com.ccteam.admin.utils.LoadMessage
import com.ccteam.admin.view.bean.UploadResult
import com.ccteam.admin.view.fragments.common.UploadFragment
import com.ccteam.admin.viewmodels.artist.ArtistEditViewModel
import com.ccteam.admin.viewmodels.common.UploadViewModel
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@AndroidEntryPoint
class ArtistEditFragment : Fragment() {

    private var _binding: FragmentArtistEditBinding? = null
    private val binding get() = _binding!!

    private val args: ArtistEditFragmentArgs by navArgs()
    private val artistEditViewModel: ArtistEditViewModel by viewModels()

    /**
     * 选择图片的内容
     * 选择完手机中的图片后，将其存储到ViewModel中并进行对应UI更新
     */
    private val selectImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
        uri?.let {
            artistEditViewModel.setArtistImgUrl(it.toString())
            artistEditViewModel.updateArtistEditInfo()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setFragmentResultListener(UploadFragment.UPLOAD_REQUEST_KEY) { _, bundle ->
            bundle.getParcelable<UploadResult>(UploadFragment.UPLOAD_URL_RESULT)?.let { result ->
                artistEditViewModel.setArtistImgUrl(result.url)
                artistEditViewModel.setArtistImgUrlSuccess(true)
                artistEditViewModel.updateArtistEditInfo()
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentArtistEditBinding.inflate(inflater,container,false)
        // 根据不同类型的歌手编辑/发布进行不同内容的设置
        binding.btnDelete.isVisible = args.artistEditType == EDIT_TYPE
        binding.statusView.isVisible = args.artistEditType == EDIT_TYPE
        if(args.artistEditType == ADD_TYPE){
            binding.btnEdit.setIconResource(R.drawable.ic_add)
            binding.btnEdit.text = getString(R.string.description_artist_edit_add)
        } else {
            binding.btnEdit.setIconResource(R.drawable.ic_edit)
            binding.btnEdit.text = getString(R.string.description_confirm_edit)
            if(args.artistId == null){
                Toast.makeText(requireContext(), "修改时未传入具体内容数值！", Toast.LENGTH_SHORT).show()
                findNavController().navigateUp()
            }
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        binding.btnEdit.setProgressButtonOnClickListener {
            artistEditViewModel.editOrAddArtistInfo()
        }

        binding.statusView.setRetryClickListener {
            artistEditViewModel.refreshArtistInfo()
        }

        binding.btnUpload.setOnClickListener {
            selectImage.launch("image/*")
        }

        binding.editArtistName.addOnEditTextAttachedListener { inputLayout ->
            inputLayout.editText?.doOnTextChanged { text, _, _, _ ->
                artistEditViewModel.setArtistName(text.toString())
                val nameSuccess = when {
                    text.toString().isEmpty() -> {
                        inputLayout.error = getString(R.string.description_artist_edit_error_name)
                        false
                    }
                    text.toString().length !in 1..100 -> {
                        inputLayout.error = getString(R.string.description_artist_edit_error_name_length)
                        false
                    }
                    else -> {
                        inputLayout.error = null
                        true
                    }
                }
                artistEditViewModel.setArtistNameSuccess(nameSuccess)
            }
        }

        binding.editImgUrl.addOnEditTextAttachedListener { inputLayout ->
            inputLayout.editText?.doOnTextChanged { text, _, _, _ ->
                artistEditViewModel.setArtistImgUrl(text.toString())
                artistEditViewModel.setArtistImgUrlSuccess(text.toString().isNotEmpty())
            }
        }

        binding.btnDelete.setProgressButtonOnClickListener {
            // 删除该歌手
            MaterialAlertDialogBuilder(requireContext())
                .setTitle(R.string.description_dialog_delete)

                .setMessage(getString(R.string.description_dialog_delete_artist_message,artistEditViewModel.editArtistInfo.value?.name))
                .setNegativeButton(R.string.description_cancel) { _,_ ->
                }
                .setPositiveButton(R.string.description_delete) { _,_ ->
                    artistEditViewModel.deleteArtistInfo()
                }.show()
        }

        artistEditViewModel.editButtonEnable.observe(viewLifecycleOwner, {
            binding.btnEdit.isEnabled = it
        })

        artistEditViewModel.deleteButtonEnable.observe(viewLifecycleOwner, {
            binding.btnDelete.isEnabled = it
        })

        artistEditViewModel.editArtistInfo.observe(viewLifecycleOwner, {
            updateUI(it)
        })

        artistEditViewModel.loadMessage.observe(viewLifecycleOwner, {
            binding.containerEdit.isVisible = it is LoadMessage.NotLoading
            binding.statusView.changeToLoadingStatus(it is LoadMessage.Loading)
            binding.statusView.changeToErrorStatus(it)
        })

        artistEditViewModel.editLoadMessage.observe(viewLifecycleOwner,EventObserver{
            binding.btnEdit.setLoading(it is LoadMessage.Loading)
            if(it is LoadMessage.Error){
                Snackbar.make(
                    binding.root,
                    it.errorMessage.description.toString(),
                    Snackbar.LENGTH_SHORT
                ).setAnchorView(binding.btnEdit).show()
            } else if(it is LoadMessage.Success){
                Snackbar.make(
                    binding.root,
                    getString(R.string.description_success),
                    Snackbar.LENGTH_SHORT
                ).setAnchorView(binding.btnEdit).show()
                setFragmentResult(REFRESH_REQUEST_KEY, bundleOf(REFRESH_REQUEST_KEY to true))
                findNavController().navigateUp()
            }
        })

        artistEditViewModel.deleteLoadMessage.observe(viewLifecycleOwner,EventObserver{
            binding.btnDelete.setLoading(it is LoadMessage.Loading)
            if(it is LoadMessage.Error){
                Snackbar.make(
                    binding.root,
                    it.errorMessage.description.toString(),
                    Snackbar.LENGTH_SHORT
                ).setAnchorView(binding.btnEdit).show()
            } else if(it is LoadMessage.Success){
                Snackbar.make(
                    binding.root,
                    getString(R.string.description_success),
                    Snackbar.LENGTH_SHORT
                ).setAnchorView(binding.btnEdit).show()
                setFragmentResult(REFRESH_REQUEST_KEY, bundleOf(REFRESH_REQUEST_KEY to true))
                findNavController().navigateUp()
            }
        })
    }

    /**
     * 为界面设置新内容
     */
    private fun updateUI(artistInfo: ArtistEditViewModel.ArtistEditInfo){
        binding.editArtistId.editText?.setText(artistInfo.id)
        binding.editArtistName.editText?.setText(artistInfo.name)
        binding.editImgUrl.editText?.setText(artistInfo.imgUrl)

        Glide.with(binding.imageArtistPhoto)
            .load(artistInfo.imgUrl)
            .placeholder(R.drawable.img_default_artist)
            .into(binding.imageArtistPhoto)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.editImgUrl.clearOnEditTextAttachedListeners()
        binding.editArtistName.clearOnEditTextAttachedListeners()

        _binding = null
    }
}